<?php
class Core_Model_Table_Stats_Request extends Model_Table
{
    /**
     * @var request.
     */
    protected $_name = 'core_stats_requests';

    public function checkCondition($select, $params)
    {
        if (isset($params['start_time']))
        {
            $select -> where('request_time<?', date('Y-m-d H:i:s',$params['start_time']));
        }
        if (isset($params['end_time']))
        {
            $select -> where('end_time<?', date('Y-m-d H:i:s',$params['end_time']));
        }
        return $select;
    }

    public function getStats($params = array())
    {
        $result = array();
        $name = $this -> _name;
        $select = $this -> select() -> from($name, array(
            'avg(mem_usage) as mem_avg',
            'avg(time_usage) as time_avg',
            'count(*) as request_count'
        ));

        return $this -> fetchRow($this -> checkCondition($select, $params)) -> toArray();
    }

    public function getStatsLast1Day()
    {
        $end_time = time();
        $start_time = $end_time - 24 * 60 * 60;

        return $this -> getStats(array(
            'start_time' => $start_time,
            'end_time' => $end_time
        ));
    }

    public function getStartLast30Day()
    {
        $end_time = time();
        $start_time = $end_time - 30 * 24 * 60 * 60;

        return $this -> getStats(array(
            'start_time' => $start_time,
            'end_time' => $end_time
        ));
    }

    public function getStatsLast7Day()
    {
        $end_time = time();
        $start_time = $end_time - 7 * 24 * 60 * 60;

        return $this -> getStats(array(
            'start_time' => $start_time,
            'end_time' => $end_time
        ));

    }

}
